<template>
  <div class="systemset-organization-staff-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button v-if="queryForm.companyid !== 0" @click="handleBack">
          返回部门
        </el-button>
        <el-form :inline="true" :model="queryForm" @submit.prevent>
          <el-space>
            <el-form-item>
              <el-select
                v-model="queryForm.SearchArea"
                placeholder="请选择公司所属区域"
                style="width: 120px"
              >
                <el-option v-if="actstaffpostid < 5" label="全部" :value="0" />
                <el-option
                  v-if="actstaffpostid < 5"
                  label="总部"
                  :value="100000"
                />
                <el-option
                  v-for="item in cityList"
                  :key="item.CityCode"
                  :label="item.AreaName"
                  :value="item.CityCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryForm.StaffPostRole"
                placeholder="按职级搜索"
                style="width: 120px"
              >
                <el-option label="按职级搜索" :value="0" />
                <el-option
                  v-for="item in StaffPostRoleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryForm.staffpostid"
                placeholder="按职位搜索"
                style="width: 120px"
              >
                <el-option label="按职位搜索" :value="0" />
                <el-option
                  v-for="item in StaffPostOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="queryForm.StaffState" style="width: 100px">
                <el-option
                  v-for="item in StaffStateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="queryForm.SearchKey"
                clearable
                placeholder="请输入姓名、账号或手机号"
              />
            </el-form-item>
            <el-form-item>
              <el-button :icon="Search" type="primary" @click="queryData">
                查询
              </el-button>
            </el-form-item>
          </el-space>
        </el-form>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <div style="margin-left: 50px">
          <el-button :icon="Plus" type="primary" @click="handleEdit">
            添加一个新员工
          </el-button>
          <!-- <el-button :icon="Delete" type="danger" @click="handleDelete">
            批量修改权限
          </el-button> -->
        </div>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      fit
      :cell-style="cellStyle"
      @selection-change="setSelectRows"
    >
      <el-table-column align="center" show-overflow-tooltip type="selection" />
      <el-table-column
        align="center"
        label="员工ID"
        prop="StaffID"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="所属组织" width="160">
        <template #default="{ row }">
          <el-text v-for="(itm, idx) in row.Company" :key="idx">
            {{ itm.CompanyName }}
            <br v-if="idx + 1 < row.Company.length" />
          </el-text>
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属部门" width="140">
        <template #default="{ row }">
          <el-text v-for="(itm, idx) in row.Department" :key="idx">
            {{ itm }}
            <br v-if="idx + 1 < row.Department.length" />
          </el-text>
        </template>
      </el-table-column>
      <el-table-column align="center" label="职级角色" width="150">
        <template #default="{ row }">
          <el-text v-for="(itm, idx) in row.StaffPostRole" :key="idx">
            {{ itm.StaffPostRoleName }}
            <br v-if="idx + 1 < row.StaffPostRole.length" />
          </el-text>
        </template>
      </el-table-column>
      <el-table-column align="center" label="职位" width="200">
        <template #default="{ row }">
          <el-text v-for="(itm, idx) in row.StaffPost" :key="idx">
            {{ itm.StaffPostName }}
            <br v-if="idx + 1 < row.StaffPost.length" />
          </el-text>
        </template>
      </el-table-column>
      <el-table-column align="center" label="员工姓名" width="120">
        <template #default="{ row }">
          <div v-if="row.StaffID === 1 && username !== 'admin'">
            {{ row.StaffName }}
          </div>
          <div v-else>
            <el-button type="primary" text @click="handleEdit(row)">
              {{ row.StaffName }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="140">
        <template #default="{ row }">
          <!-- <el-select v-model="row.StaffState" style="width: 100px">
            <el-option
              v-for="item in StaffStateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select> -->
          <div>{{ getStaffState(row.StaffState) }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="登录账号"
        prop="LoginName"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        label="手机号"
        prop="Mobile"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column align="center" label="操作" width="210">
        <template #default="{ row }">
          <div v-if="row.StaffID === 1 && username !== 'admin'">----</div>
          <div v-else>
            <el-button v-if="StaffPostRoleID === 0" text @click="authEdit(row)">
              权限设置
            </el-button>
            <el-button text @click="handleEdit(row)">密码设置</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="120">
        <template #default="{ row }">
          <div v-if="row.StaffID === 1 && username !== 'admin'">----</div>
          <div v-else>
            <el-button text @click="handleEdit(row)">信息编辑</el-button>
            <!-- <el-button text @click="handleDelete(row)">删除</el-button> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit
      ref="editRef"
      :companyoptions="CompanyOptions"
      :staffpostroleoptions="StaffPostRoleOptions"
      @fetch-data="fetchData"
    />
    <authset
      ref="authRef"
      :companyoptions="CompanyOptions"
      :businessclassoptions="BusinessClassOptions"
      @fetch-data="fetchData"
    />
  </div>
</template>

<script>
  import {
    getOpenAreaCity,
    getBusinessClassSelect,
    getCompanySelect,
    getStaffPostRoleSelect,
    getStaffPostSelect,
  } from '@/api/common'
  import { getList, doDelete } from '@/api/systemsetOrganizationStaff'
  import Edit from './components/SystemsetOrganizationStaffEdit'
  import Authset from './components/StaffAuthSet'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'
  import { useUserStore } from '@/store/modules/user'

  export default defineComponent({
    name: 'SystemsetOrganizationStaff',
    components: { Edit, Authset },
    setup() {
      const router = useRouter()
      const route = useRoute()
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const userStore = useUserStore()
      const { username } = storeToRefs(userStore)

      const state = reactive({
        StaffPostRoleID: 0,
        actstaffpostid: 0,
        cityList: [],
        username: username.value,
        editRef: null,
        authRef: null,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          level: 0,
          companyid: 0,
          upDepartmentID: 0,
          departmentid: 0,
          StaffPostRole: 0,
          staffpostid: 0,
          StaffState: 1,
          pageNo: 1,
          pageSize: 10,
          SearchKey: '',
          SearchArea: 0,
        },
        StaffStateOptions: [
          { label: '在职', value: 1 },
          { label: '暂停账号使用', value: -1 },
          { label: '已离职', value: -2 },
          { label: '未设定', value: 0 },
        ],
        BusinessClassOptions: [],
        CompanyOptions: [],
        StaffPostRoleOptions: [],
        StaffPostOptions: [],
      })

      const cellStyle = (obj) => {
        if (obj.columnIndex === 6) {
          return { color: '#1890FF' }
        }
      }

      const getStaffState = (StaffState) => {
        const StaffStates = state.StaffStateOptions.find(
          (item) => item.value === StaffState
        )
        console.log('StaffStates', StaffStates)
        return StaffStates.label
      }

      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const authEdit = (row) => {
        if (row.StaffID) {
          console.log(row, '123')
          state.authRef.showEdit(row, 'User')
        }
      }
      const handleEdit = (row) => {
        if (row.StaffID) {
          state.editRef.showEdit(row)
        } else {
          state.editRef.showEdit()
        }
      }
      const handleDelete = (row) => {
        if (row.id) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.id).join()
            $baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { list, total },
        } = await getList(state.queryForm)
        state.list = list
        state.total = total
        state.listLoading = false
      }

      const getOptions = async () => {
        state.listLoading = true
        const { data } = await getOpenAreaCity()
        state.cityList = data
        const {
          data: { BusinessClassOptions },
        } = await getBusinessClassSelect()
        const {
          data: { CompanyOptions },
        } = await getCompanySelect()
        const {
          data: { StaffPostRoleOptions },
        } = await getStaffPostRoleSelect()
        const {
          data: { StaffPostOptions },
        } = await getStaffPostSelect()
        state.BusinessClassOptions = BusinessClassOptions
        state.CompanyOptions = CompanyOptions
        state.StaffPostRoleOptions = StaffPostRoleOptions
        state.StaffPostOptions = StaffPostOptions
        state.listLoading = false
      }

      onMounted(() => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        state.StaffPostRoleID = userInfo.StaffPostRoleID
        const actstaffpost = JSON.parse(userInfo.StaffPostID)
        state.actstaffpostid = actstaffpost[0][1]

        if (route.query.level) {
          state.queryForm.level = route.query.level
        }
        if (route.query.companyid) {
          state.queryForm.companyid = route.query.companyid
        }

        if (route.query.upDepartmentID) {
          state.queryForm.upDepartmentID = route.query.upDepartmentID
        }
        if (route.query.departmentid) {
          state.queryForm.departmentid = route.query.departmentid
        }
        if (route.query.staffpostid) {
          state.queryForm.staffpostid = route.query.staffpostid
        }
        if (route.query.StaffPostRole) {
          state.queryForm.StaffPostRole = route.query.StaffPostRole
        }
        fetchData()
        getOptions()
      })
      watch(
        () => route.params,
        () => {
          // 当路由参数变化时，重新加载数据或执行其他逻辑
          const userInfo = JSON.parse(localStorage.getItem('userInfo'))
          state.StaffPostRoleID = userInfo.StaffPostRoleID
          const actstaffpost = JSON.parse(userInfo.StaffPostID)
          state.actstaffpostid = actstaffpost[0][1]

          if (route.query.level) {
            state.queryForm.level = route.query.level
          }
          if (route.query.companyid) {
            state.queryForm.companyid = route.query.companyid
          }

          if (route.query.upDepartmentID) {
            state.queryForm.upDepartmentID = route.query.upDepartmentID
          }
          if (route.query.departmentid) {
            state.queryForm.departmentid = route.query.departmentid
          }
          if (route.query.staffpostid) {
            state.queryForm.staffpostid = route.query.staffpostid
          }
          if (route.query.StaffPostRole) {
            state.queryForm.StaffPostRole = route.query.StaffPostRole
          }
          fetchData()
          getOptions()
        },
        { immediate: true }
      )
      const handleBack = () => {
        console.log('返回部门')
        router.go(-1)
      }

      return {
        ...toRefs(state),
        handleBack,
        cellStyle,
        setSelectRows,
        authEdit,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        Delete,
        Plus,
        Search,
        getStaffState,
      }
    },
  })
</script>
